package middleware

import (
	"net/http"

	"github.com/go-playground/validator"
	"github.com/gofiber/fiber/v2"
)

func BindAndValidate[T any]() fiber.Handler {
	return func(c *fiber.Ctx) error {
		var req T
		if err := c.BodyParser(&req); err != nil {
			return c.Status(http.StatusBadRequest).JSON(fiber.Map{
				"msg": "Param parse failed",
				"err": err.Error(),
			})
		}

		v := validator.New()
		if err := v.Struct(req); err != nil {
			return c.Status(http.StatusBadRequest).JSON(fiber.Map{
				"msg": "Param validate failed",
				"err": err.Error(),
			})
		}

		c.Locals("req", req)
		return c.Next()
	}
}

func GetBindData[T any](c *fiber.Ctx) (T, bool) {
	val := c.Locals("req")
	if val == nil {
		var zero T
		return zero, false
	}
	req, ok := val.(T)
	return req, ok
}
